from django.views.generic import TemplateView
import os
from elasticsearch import Elasticsearch
from django.http import JsonResponse


# https://free-api.heweather.com/v5/weather?city=%E6%B2%88%E9%98%B3&key=5f5cbc0222bf49709c1c7f14d7016702
class TvsearchView(TemplateView):
    template_name = "hello.html"

    def get_context_data(self, **kwargs):
        return {'hello': "Hello World!"}
    # def dispatch(self, request):
    #     return super(TvsearchView, self).dispatch(request)

    def get(self, request):
        # print('self.is_student', self.is_student)
        # print('self.task', self.task)
        es = Elasticsearch(http_auth=('elastic', 'changeme'), timeout=10)
        # es = Elasticsearch(os.environ['ES_ENDPOINT'])
        query = request.GET['q']
        query_json = {
            'query': {
                "bool": {
                    "must": {
                        "match": {
                            "tv_name": query
                        }
                    },
                    # "filter": {
                    #     "range": {
                    #         "age": {"gt": 30}
                    #     }
                    # }
                }
            }
        }
        res = es.search(index="qqtv", doc_type='tv_info', body=query_json)
        # 获取所有数据
        # 获取第一条数据，得分最高。
        top_10_recodes = res['hits']['hits']
        # print(top_10_recodes[1])
        # print json.dumps(top_10_recodes)
        data = {
            'top_10_recodes': top_10_recodes,
        }
        return JsonResponse(data)

    # def post(self, request, interview_id, course_id):
    #     return self.render_to_response({
    #         'view': self,
    #         'exam': self.exam,
    #         'is_exam_ended': self.exam.is_ended(),
    #     })
